package edu.lingnan.reactproject.controller;

import edu.lingnan.reactproject.pojo.RoleMenus;
import edu.lingnan.reactproject.pojo.Roles;
import edu.lingnan.reactproject.pojo.Users;
import edu.lingnan.reactproject.service.RoleMenusService;
import edu.lingnan.reactproject.service.RolesService;
import edu.lingnan.reactproject.service.UsersService;
import edu.lingnan.reactproject.vo.LoginParams;
import edu.lingnan.reactproject.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.management.relation.Role;
import java.util.HashMap;
import java.util.List;

/**
 * @author dualseason
 */
@RestController
public class BaseController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RolesService rolesService;

    @Autowired
    private RoleMenusService roleMenusService;

    @PostMapping("/")
    public Result hello(){
        return new Result(0,"hello");
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginParams login) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("username", login.getUsername());
        map.put("password", login.getPassword());
        List<Users> users = usersService.listByMap(map);
        if (users.size() > 0 && users != null) {
            Users user = users.get(0);
            HashMap<String, Object> queryRoleIdMap = new HashMap<>(1);
            queryRoleIdMap.put("role_menu_id",user.getRoleId());
            List<RoleMenus> menus = roleMenusService.listByMap(queryRoleIdMap);
            Roles role = rolesService.getById(user.getRoleId());
            HashMap<String, Object> hashMap = new HashMap<>(5);
            hashMap.put("_id",user.getId());
            hashMap.put("password",user.getPassword());
            hashMap.put("username",user.getUsername());
            hashMap.put("create_time",user.getCreateTime());
            HashMap<String, Object> roles = new HashMap<>();
            roles.put("menus",menus);
            roles.put("_id",role.getId());
            roles.put("name",role.getName());
            roles.put("create_time",role.getCreateTime());
            roles.put("auth_name",role.getAuthName());
            roles.put("auth_time",role.getAuthTime());
            hashMap.put("role",roles);
            return new Result(0,hashMap);
        }else {
            return new Result(1,"登录异常,请重新尝试");
        }
    }
}
